/*
 * @Description: 用户相关
 * @Author: yiling (315800015@qq.com)
 * @Date: 2021-04-29 15:42:36
 * @LastEditors: yiling (315800015@qq.com)
 * @LastEditTime: 2021-07-12 14:33:30
 * @FilePath: \tm_uni_app\src\store\modules\user.js
 */
import store from 'store'

const state = {
  isLogin: uni.getStorageSync('isLogin') || false, // 是否已登录
  userInfo: uni.getStorageSync('userInfo') || {},
  token: '', // token
  mobile: uni.getStorageSync('mobile') || '', // mobile
  tokenHead: '', // tokenHead
  isLoginJumpLock: false, // 登录跳转锁
  regUser:uni.getStorageSync('regUser') || {}, // 新用户注册信息
}

const getters = {
  token: (state) => state.token,
  tokenHead: (state) => state.tokenHead,
  regUser: (state) => state.regUser,
}
// 用于异步，可在这里放请求，但无法直接修改state中的内容
const actions = {
  // 设置登录锁
  setLoginLock({ commit }, value) {
    console.log('actions setLoginLock', value)
    commit('setIsLoginJumpLock', value)
  },
  // 跳登录
  goLogin({ commit }, value) {
    commit('setGoLogin', value)
  },

  // 退出登录
  logout({ commit }) {
    // uni.getStorageSync('token') && http('user.logout')
    uni.removeStorageSync('token')
    uni.removeStorageSync('tokenHead')
    uni.removeStorageSync('session_key')
    uni.removeStorageSync('userInfo')
    uni.removeStorageSync('cartNum')
    uni.removeStorageSync('chatSessionId')
    commit('IS_LOGIN', false)
    commit('USER_INFO', {})
    commit('CART_LIST', [])
    commit('CART_NUM')
    commit('USER_DATA', {})
  },


}
// 用于同步，可直接修改state
const mutations = {
  // 登录态
  IS_LOGIN(state, data) {
    uni.setStorageSync('isLogin', data)
    console.log('IS_LOGIN', data)
    state.isLogin = data
  },
  // 登录锁
  setIsLoginJumpLock(state, value) {
    console.log('%c 跳转登录锁', 'color:#f00', value)
    state.isLoginJumpLock = value
  },
  // 跳登录
  setGoLogin(state, value) {
    console.log('%c 跳转登录锁', 'color:#f00', value)
    if (value) {
      this.$u.toast('请先登录 vuex')
    }
  },
  // 用户信息
  setUserInfo(state, val) {
    state.userInfo = val
    console.log('设置userInfo', val, Date.now())
  },
  // 设置token
  setToken(state, val) {
    state.token = val
    uni.setStorageSync('token', val)
    store.commit('user/IS_LOGIN', true)
    console.log('设置token', val, Date.now())
  },
  // 设置tokenHead
  setTokenHead(state, val) {
    state.tokenHead = val
    uni.setStorageSync('tokenHead', val)
    console.log('设置tokenHead', val, Date.now())
  },
    // 用户信息
   setRegUser(state, val) {
        state.regUser =  Object.assign(state.regUser,val)
        uni.setStorageSync('regUser', state.regUser)
        console.log('新注册用户user', val, Date.now())
    },
}

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations,
}
